import {AfterViewInit, Component, OnInit} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzModalService} from 'ng-zorro-antd/modal';
import {ActivatedRoute, Router} from '@angular/router';
import {UsedStorePService} from '../../used-store-p.service';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {getLodop} from '../../../../../assets/LodopFuncs';
import {PermissionService} from '../../../../service/permission.service';
import {CommonService} from '../../../../services-common/common.service';

enum STATUS {
  草稿 = 1,
  待审核,
  待打包,
  待出库,
  已出库,
  已签收,
  已取消,
  审核不通过,
  物流异常,
}

interface TrackModal {
  visible: boolean; // 模态框显隐
  loading: boolean; // 按钮是否加载中
  id: string; // id
  url: string; // 文件
  remark: string; // 跟进内容
  file: any; // 跟进文件
}

@Component({
  selector: 'app-out-store-list',
  templateUrl: './out-store-list.component.html',
  styleUrls: ['./out-store-list.component.scss']
})
export class OutStoreListComponent implements OnInit {
  STATUS = STATUS;
  LODOP: any;
  dbclick: any;
  query = {
    isFreight: '',
    deliveryNumber: '', // 出库单号
    state: [], // 状态
    type: [], // 出库类型
    createTime: [], // 创建时间
    outTime: [], // 出库时间
    goods: '', // 包含商品
    expressNo: '', // 物流单号
    orderNum: '', // 关联单号
    page: 1, // 当前页
    pageSize: 20, // 分页大小
  };
  listOfData = {
    total: 0,
    records: []
  };
  modal = {
    modalVisible: false,
    operationType: '',
    loading: false,
  };
  formData = {
    id: '',
    date: '',
    productId: '',
    registerCount: 0,
    rechargeAmount: 0,
  };
  outStoreTypes: any;
  checkModal = {
    id: '',
    deliveryMethod: '',
    visible: false,
    remark: ''
  };
  //  跟进
  trackModal: TrackModal = {
    visible: false,
    loading: false,
    id: '',
    url: '',
    remark: '',
    file: [],
  };
  trackHistoryList: any[] = [];
  logistics: any[] = [];
  printList: any[] = [];
  logisticsModal = {
    visible: false,
    loading: false,
    id: '',
    deliveryMethod: 3,
    isFreight: 1,
    freight: '',
    company: '',
    no: '',
  };
  // 选择
  checked = false;
  indeterminate = false;
  setOfCheckedId = new Set<number>();
  printLogisticsInfo: any;
  printLogisticsInfoJD: any;
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    console.log(file);
    this.trackModal.file = [file];
    return false;
  };

  constructor(
    private nzMessageService: NzMessageService,
    private nzModalService: NzModalService,
    private router: Router,
    private usedStorePService: UsedStorePService,
    public permissionService: PermissionService,
    public activatedRoute: ActivatedRoute,
    private commonService: CommonService
  ) {
  }

  async ngOnInit() {
    await this.usedStorePService.dictData('machine_inbound_type').then((res: any) => {
      if (res.code === 0) {
        this.outStoreTypes = res.data.list.records;
      }
    });
    await this.usedStorePService.dictData('logistics_company').then((res: any) => {
      if (res.code === 0) {
        this.logistics = res.data.list.records;
      }
    });
    if (this.activatedRoute.snapshot.queryParams.logisticsCode) {
      this.query.expressNo = this.activatedRoute.snapshot.queryParams.logisticsCode;
    }
    this.queryList();
    setTimeout(() => {
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      if (!this.LODOP) {
        this.nzMessageService.warning('未安装打印插件');
        return;
      }
      let count = 0;
      for (let i = 0; i < this.LODOP.GET_PRINTER_COUNT(); i++) {
        if (this.LODOP.GET_PRINTER_NAME(i).includes('BTP')) {
          count += 1;
          this.LODOP.SET_PRINTER_INDEXA(i);
        }
      }
      if (count === 0) {
        this.nzMessageService.warning('未找到包含BTP的打印机，请手动设置');
      } else if (count === 1) {
        this.nzMessageService.success('打印机初始化成功');
      } else if (count > 1) {
        this.nzMessageService.success('找到两台包含BTP的打印机，将选择最后一台作为默认设备');
      }
    }, 1000);
  }

  onAllChecked(checked: boolean): void {
    this.listOfData.records
      // @ts-ignore
      .filter(({disabled}) => !disabled)
      // @ts-ignore
      .forEach(({id}) => this.updateCheckedSet(id, checked));
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    // @ts-ignore
    const listOfEnabledData = this.listOfData.records.filter(({disabled}) => !disabled);
    // @ts-ignore
    this.checked = listOfEnabledData.every(({id}) => this.setOfCheckedId.has(id));
    // @ts-ignore
    this.indeterminate = listOfEnabledData.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }


  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  queryBtn() {
    this.query.page = 1;
    this.queryList();
  }

  resetQuery() {
    this.query = {
      isFreight: '',
      deliveryNumber: '', // 出库单号
      state: [], // 状态
      type: [], // 出库类型
      createTime: [], // 创建时间
      outTime: [], // 出库时间
      goods: '', // 包含商品
      expressNo: '', // 物流单号
      orderNum: '', // 关联单号
      page: 1, // 当前页
      pageSize: 20, // 分页大小
    };
    this.queryList();
  }

  // 查询列表
  queryList(): void {
    this.usedStorePService.getOutStoreList({
      ...this.query,
      type: this.query.type.join(','),
      state: this.query.state.join(','),
      // @ts-ignore
      beginTime: this.usedStorePService.formatTime(this.query.createTime ? this.query.createTime[0] : '', 'date'),
      // @ts-ignore
      endTime: this.usedStorePService.formatTime(this.query.createTime ? this.query.createTime[1] : '', 'date'),
      // @ts-ignore
      deliveryTime: this.usedStorePService.formatTime(this.query.outTime ? this.query.outTime[0] : '', 'date'),
      // @ts-ignore
      endDeliveryTime: this.usedStorePService.formatTime(this.query.outTime ? this.query.outTime[1] : '', 'date'),
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
      }
    });
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.queryList();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.queryList();
  }

  // 删除
  deleteRow(id: any) {
    this.usedStorePService.outStoreSave({
      recycleDelivery: {
        id,
        deleteState: 1
      },
      list: []
    }, true).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('删除成功');
        this.queryList();
      }
    });
  }

  // 放到二手商城销售或者取回
  usedChannel(data: any, status: 0 | 2) {
    const message = '确认退回？';
    this.nzModalService.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: `<b>${message}</b>`,
      nzOnOk: () => {
        this.usedStorePService.channelOccupy(data.equipmentCode, status).then((res: any) => {
          if (res.code === 0) {
            this.nzMessageService.success('操作成功');
            this.queryList();
          }
        });
      }
    });
  }


  view(id: any) {
    this.router.navigate(['/used-store/usedOutAdd'], {queryParams: {id}});
  }

  toDetail(id: any) {
    this.router.navigate(['/used-store/usedOutDetail'], {queryParams: {id}});
  }

  changeStatus(data: any, status: any) {
    this.usedStorePService.outStoreCheck(data.id, status).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.queryList();
      }
    });
  }

  batchChangeStatus(status: any) {
    if (this.setOfCheckedId.size === 0) {
      this.nzMessageService.success('请选择要操作的数据');
      return;
    }
    this.usedStorePService.outStoreCheck(
      this.listOfData.records.filter((i: any) => this.setOfCheckedId.has(i.id)).map((i: any) => i.id).join(','), status).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success(res.data);
        this.queryList();
        this.setOfCheckedId.clear();
        this.refreshCheckedStatus();
      }
    });
  }

  cancelSF(data: any) {
    this.usedStorePService.cancelSF(data.id).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('取消成功，请及时将该单对应的机器回归正确的库位，避免库存混乱');
        this.queryList();
      }
    });
  }

  add() {
    this.router.navigate(['/used-store/usedOutAdd']);
  }

  outStoreType(type: any) {
    const item = this.outStoreTypes.filter((o: any) => o.content * 1 === type * 1);
    let result = '';
    if (item.length) {
      result = item[0].name;
    }
    return result;
  }

  setPrint() {
    this.LODOP.SELECT_PRINTER();
  }

  batchPrint() {
    if (this.setOfCheckedId.size === 0) {
      this.nzMessageService.success('请选择要打印的数据');
      return;
    }
    this.printList = this.listOfData.records.filter((i: any) => this.setOfCheckedId.has(i.id) && [3, 4, 5].includes(i.state));
    if (!this.printList.length) {
      this.nzMessageService.error('没有可打印面单的数据');
      return;
    }
    this.printNow();
  }

  async printNow() {
    const data = this.printList.shift();
    const addresserRes = await this.usedStorePService.getAddresser(data.type === 2 ? 14 : 15);
    let addresser = {
      region: '',
      tel: '',
      contacts: ''
    };
    if (addresserRes.code === 0) {
      addresser = addresserRes.data;
      addresser.region = addresser.region.replace(/\s/g, '');
      addresser.tel = addresser.tel.slice(0, 3) + '****' + addresser.tel.slice(7);
    }
    await this.usedStorePService.logisticsSF(data.expressNo, data.id).then(res => {
      if (res.data.head === 'ERR') {
        this.nzMessageService.error(res.data.err_msg);
        return;
      }
      if (res.code === 0) {
        if (data.expressNo.match(/jd/i)) {
          this.printLogisticsInfoJD = res.data;
          setTimeout(() => {
            this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printLogisticsJD')?.innerHTML);
            this.LODOP.PRINT();
            this.nzMessageService.success('打印成功');
          });
        } else {
          this.printLogisticsInfo = {
            ...res.data.body[0].print[0],
            address: data.address.replace(/\s/g, ''),
            tel: data.tel.slice(0, 3) + '****' + data.tel.slice(7),
            consignee: data.consignee,
            number: data.number,
            payMethod: res.data.payMethod,
            addresser
          };
          setTimeout(() => {
            this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printExpressSf')?.innerHTML);
            this.LODOP.PRINT();
            this.nzMessageService.success('打印成功');
          });
        }
      }
    });
    if (this.printList.length) {
      setTimeout(() => {
        this.printNow();
      }, 3000);
    } else {
      this.setOfCheckedId = new Set();
      this.refreshCheckedStatus();
    }
  }

  async print(data: any) {
    if (!this.LODOP) {
      this.nzMessageService.warning('打印插件未成功初始化，请检查是否已安装');
      return;
    }
    this.LODOP.SET_LICENSES('', 'D4E01F380814536C3C4887A0707CBBD4A4B', '', '');
    if (!data.expressNo) {
      this.nzMessageService.warning('物流单号不能为空');
      return;
    }
    if (this.dbclick) {
      clearTimeout(this.dbclick);
      this.dbclick = null;
      this.LODOP.SET_PRINT_PAGESIZE(1, 760, 1300);
      const addresserRes = await this.usedStorePService.getAddresser(data.type === 2 ? 14 : 15);
      let addresser = {
        region: '',
        tel: '',
        contacts: ''
      };
      if (addresserRes.code === 0) {
        addresser = addresserRes.data;
        addresser.region = addresser.region.replace(/\s/g, '');
        addresser.tel = addresser.tel.slice(0, 3) + '****' + addresser.tel.slice(7);
      }
      await this.usedStorePService.logisticsSF(data.expressNo, data.id).then(res => {
        if (res.data.head === 'ERR') {
          this.nzMessageService.error(res.data.err_msg);
          return;
        }
        if (res.code === 0) {
          if (data.expressNo.match(/jd/i)) {
            this.printLogisticsInfoJD = res.data;
            // setTimeout(() => {
            //   this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printLogisticsJD')?.innerHTML);
            //   this.LODOP.PREVIEW();
            // });
          } else {
            this.printLogisticsInfo = {
              ...res.data.body[0].print[0],
              address: data.address.replace(/\s/g, ''),
              tel: data.tel.slice(0, 3) + '****' + data.tel.slice(7),
              consignee: data.consignee,
              number: data.number,
              payMethod: res.data.payMethod,
              addresser
            };
            setTimeout(() => {
              this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printExpressSf')?.innerHTML);
              this.LODOP.PREVIEW();
            });
          }
        }
      });
      return;
    }
    this.LODOP.SET_PRINT_PAGESIZE(1, 760, 1300);
    this.dbclick = setTimeout(async () => {
      this.dbclick = null;
      const addresserRes = await this.usedStorePService.getAddresser(data.type === 2 ? 14 : 15);
      let addresser = {
        region: '',
        tel: '',
        contacts: ''
      };
      if (addresserRes.code === 0) {
        addresser = addresserRes.data;
        addresser.region = addresser.region.replace(/\s/g, '');
        addresser.tel = addresser.tel.slice(0, 3) + '****' + addresser.tel.slice(7);
      }
      await this.usedStorePService.logisticsSF(data.expressNo, data.id).then(res => {
        if (res.data.head === 'ERR') {
          this.nzMessageService.error(res.data.err_msg);
          return;
        }
        if (res.code === 0) {
          if (data.expressNo.match(/jd/i)) {
            this.printLogisticsInfoJD = res.data;
            setTimeout(() => {
              this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printLogisticsJD')?.innerHTML);
              this.LODOP.PRINT();
              this.nzMessageService.success('打印成功');
            });
          } else {
            this.printLogisticsInfo = {
              ...res.data.body[0].print[0],
              address: data.address.replace(/\s/g, ''),
              tel: data.tel.slice(0, 3) + '****' + data.tel.slice(7),
              consignee: data.consignee,
              number: data.number,
              payMethod: res.data.payMethod,
              addresser
            };
            setTimeout(() => {
              this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printExpressSf')?.innerHTML);
              this.LODOP.PRINT();
              // this.nzMessageService.success('打印成功');
            });
          }
        }
      });
    }, 500);
  }

  checkResolve() {
    this.usedStorePService.outStoreCheck(this.checkModal.id, 3, this.checkModal.remark, this.checkModal.deliveryMethod).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.queryList();
        this.hideCheckModal();
      }
    });
  }

  checkReject() {
    if (!this.checkModal.remark) {
      this.nzMessageService.warning('审核不通过时需要输入备注');
      return;
    }
    this.usedStorePService.outStoreCheck(this.checkModal.id, 8, this.checkModal.remark, this.checkModal.deliveryMethod).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.queryList();
        this.hideCheckModal();
      }
    });
  }

  showCheckModal(data: any) {
    this.checkModal = {
      id: data.id,
      deliveryMethod: data.deliveryMethod,
      visible: true,
      remark: ''
    };
  }

  hideCheckModal() {
    this.checkModal = {
      id: '',
      deliveryMethod: '',
      visible: false,
      remark: ''
    };
  }

  // 显示跟进模态框
  showTrackModal(id: string) {
    this.usedStorePService.outStoreHistory(id).then(res => {
      this.trackHistoryList = res.data.records;
      this.trackModal.id = id;
      this.trackModal.visible = true;
    });
  }

  // 隐藏跟进模态框
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.loading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.usedStorePService.httpPost(this.usedStorePService.serviceUrl.fileUpload, file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.url = res.data;
          }
        });
      }
      // enclosure	附件
      // content	跟进内容
      // type	1、订单 2、售后 3、客户 4、出库 5直降  6退税 7机器
      // relationInformation	关联id
      // remarks	跟进备注
      // modelId	类型 1旧的表示二手回收 2表示二手商城 3表示二手回收
      this.usedStorePService.outStoreTrack({
        enclosure: this.trackModal.url,
        content: this.trackModal.remark,
        type: 4,
        relationInformation: this.trackModal.id,
        remarks: '',
        modelId: 2,
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.trackModal = {
            visible: false,
            loading: false,
            id: '',
            url: '',
            remark: '',
            file: [],
          };
        } else {
          this.trackModal.loading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.trackModal = {
        visible: false,
        loading: false,
        id: '',
        url: '',
        remark: '',
        file: [],
      };
    }
  }

  showLogisticsModal(data: any) {
    this.logisticsModal.id = data.id;
    this.logisticsModal.deliveryMethod = data.deliveryMethod;
    if (data.state === 9) {
      this.logisticsModal.deliveryMethod = 2;
    }
    this.logisticsModal.isFreight = data.isFreight;
    this.logisticsModal.freight = data.freight;
    this.logisticsModal.visible = true;
    // @ts-ignore
    this.logisticsModal.company = data.expressCode;
    this.logisticsModal.no = data.expressNo;
  }

  hideLogisticsModal() {
    this.logisticsModal = {
      visible: false,
      loading: false,
      id: '',
      deliveryMethod: 3,
      isFreight: 1,
      freight: '',
      company: '',
      no: '',
    };
  }

  // 出库
  outStore(data: any) {
    if (!data.expressNo && data.deliveryMethod !== 3) {
      this.nzMessageService.warning('请先完善物流信息');
      this.showLogisticsModal(data);
      return;
    }
    this.changeStatus(data, 5);
  }

  // 修改物流信息
  modifyLogistics() {
    // if (this.logisticsModal.deliveryMethod === 1) {
    //   this.usedStorePService.outStoreCheck(this.logisticsModal.id, 3, '', 1).then(res => {
    //     if (res.code === 0) {
    //       this.nzMessageService.success('操作成功');
    //       this.queryList();
    //       this.hideLogisticsModal();
    //     }
    //   });
    //   return;
    // }
    this.usedStorePService.outStoreLogistics(
      this.logisticsModal.id,
      this.logisticsModal.deliveryMethod,
      this.logisticsModal.deliveryMethod === 2 ? this.logisticsModal.company : null,
      this.logisticsModal.deliveryMethod === 2 ? this.logisticsModal.no : null,
      this.logisticsModal.deliveryMethod === 2 ? this.logisticsModal.isFreight : null,
      this.logisticsModal.deliveryMethod === 2 ? this.logisticsModal.freight : null,
      this.logisticsModal.deliveryMethod === 2 ? this.logistics.filter(i => i.content === this.logisticsModal.company)[0].name : null
    ).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.queryList();
        this.hideLogisticsModal();
      }
    });
  }

  // 导出出库单
  async exportOutOrderData(item: any) {
    try {
      const params = {
        id: item.id
      };
      const res: any = await this.usedStorePService.exportOutOrderData(params);
    } catch (error: any) {
      const {status, url}: any = error;
      this.commonService.downLoadUrlFile(url);
    }
  }
}
